//
//  SRSportTask+Cate.m
//  SportRing
//
//  Created by mykoma on 14/11/2.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRSportTask+Cate.h"
#import "SRDB.h"

@implementation SRSportTask (Cate)

+ (SRSportTask *)task
{
    __block SRSportTask * task = nil;
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         task = [SRSportTask MR_createEntity];
     }];
    return task;
}

- (void)configAttributesWithBlock:(void(^)(SRSportTask * aSelf))block
{
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         block(self);
     }];
}

@end

@implementation SRSportTask (Find)

+ (NSArray *)findAllUnuploadTasks:(SRMe *)me
{
    __block NSMutableArray * mArray = [@[] mutableCopy];
    [me.days enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        SRDay * day = obj;
        if (day.task != nil && day.task.isSynced.boolValue == NO) {
            [mArray addObject:day.task];
        }
    }];
    return mArray;
}

+ (SRSportTask *)findTaskForDay:(NSString *)dayStr
{
    SRDay * day = [SRDay findDayCINEForDateStr:dayStr forMe:[SRMe currentUser]];
    return day.task;
}

+ (SRSportTask *)findTaskForMonth:(NSString *)monthStr
{
    SRMonth * month = [SRMonth findMonthCINEForMonthStr:monthStr forMe:[SRMe currentUser]];
    return month.task;
}

+ (SRSportTask *)findTaskCINEForDay:(NSString *)dayStr
{
    SRSportTask * task = [SRSportTask findTaskForDay:dayStr];
    if (task == nil) {
        task = [SRSportTask task];
        [task configAttributesWithBlock:^(SRSportTask *aSelf) {
            SRDay * day = [SRDay findDayCINEForDateStr:dayStr forMe:[SRMe currentUser]];
            aSelf.day = day;
            aSelf.startTime = @"";
            aSelf.endTime = @"";
        }];
    }
    return task;
}

+ (SRSportTask *)findTaskCINEForMonth:(NSString *)monthStr
{
    SRSportTask * task = [SRSportTask findTaskForMonth:monthStr];
    if (task == nil) {
        task = [SRSportTask task];
        [task configAttributesWithBlock:^(SRSportTask *aSelf) {
            SRMonth * month = [SRMonth findMonthForMonthStr:monthStr forMe:[SRMe currentUser]];
            aSelf.month = month;
        }];
    }
    return task;
}

- (BOOL)isCompleted
{
    return self.completedCounter.integerValue >= self.totalCounter.integerValue;
}

@end